package com.zhang.generateexcel.util;

import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.var;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    public static List<MultipartFile> getFiles(MultipartRequest request) {
        var names = request.getFileNames(); //参数名不是文件名
        var files = new ArrayList<MultipartFile>();
        while (names.hasNext()) {
            files.addAll(request.getFiles(names.next()));
        }
        return files;
    }

    public static String getText(String url) {
        return cn.hutool.http.HttpUtil.get(url);
    }

    public static String getText(String url, Map<String, Object> args) {
        return cn.hutool.http.HttpUtil.get(url, args);
    }

    public static JSONObject getJObject(String url, Map<String, Object> args) {
        return JSONUtil.parseObj((getText(url, args)));
    }

    public static String argsString(Map<String, Object> args) {
        var sb = new StringBuilder();
        for (var key : args.keySet()) {
            if (sb.length() != 0) {
                sb.append('&');
            }
            sb.append(key);
            sb.append('=');
            sb.append(args.get(key));
        }
        return sb.toString();
    }

    public static HttpResponse postForm(String url, Map<String, Object> args) {
        var post = cn.hutool.http.HttpUtil.createPost(url);
        post.body(argsString(args));
        post.contentType("application/x-www-form-urlencoded");
        return post.execute();
    }

    public static HttpResponse postJson(String url, Map<String, Object> args, JSONObject json) {
        var post = cn.hutool.http.HttpUtil.createPost(url
                + (args != null && args.size() > 0 ? "?" + argsString(args) : ""));
        post.body(json.toString());
        post.contentType("application/json");
        return post.execute();
    }

    public static InputStream postJsonGetStream(String url, Map<String, Object> args, JSONObject json) {
        return postJson(url, args, json).bodyStream();
    }

}
